import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import router from '@/router/index'
import { dynamicRoutes, errorRoute } from '@/router/routes'
import { cloneDeep } from 'lodash'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    routes: [],
    buttons: [],
    allowRoutes: []
  }
}

const state = getDefaultState()

// 添加路由的方法
const addDynamicRoute = (routes) => {
  routes.forEach(route => {
    router.addRoute(route)
  })
}

// 过滤动态路由的方法
const getDynamicRoute = (routeNameList, routeList) => {
  return routeList.filter(route => {
    if (route.children) {
      route.children = getDynamicRoute(routeNameList, route.children)
    }
    return routeNameList.includes(route.name)
  })
}

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_BUTTONS: (state, buttons) => {
    state.buttons = buttons
  },
  SET_ROUTES: (state, routes) => { // 设置动态路由
    state.routes = routes
  },
  ADD_ROUTE: (state) => {
    state.allowRoutes = getDynamicRoute(state.routes, cloneDeep(dynamicRoutes))
    addDynamicRoute([...state.allowRoutes, ...errorRoute])
  }
}

const actions = {
  // 用户登录
  // 1.设置 vuex 中的 token  2. 将 token 保存到 cookie
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取用户信息
  // 1. 将name 和 头像 保存到 vuex
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response
        if (!data) {
          return reject('Verification failed, please Login again.')
        }
        const { name, avatar, buttons, routes } = data




        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_BUTTONS', buttons)
        commit('SET_ROUTES', routes)
        commit('ADD_ROUTE')
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 添加动态路由
  // addRoute({ commit }, state) {
  //   console.log('添加路由')
  //   commit('ADD_ROUTE')
  // },
  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

